package action.back;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.springframework.beans.factory.annotation.Autowired;

import service.SettingService;

import models.Setting;
import net.sf.json.JSONArray;

public class SettingAction extends DefaultAction {
	
	private Setting setting;
	
	@Autowired
	private SettingService settingService;
	public String index() {
		return "index";
	}
	

	public void update() {
		getCommonService().update(setting);
		settingService.updateSettingMap(setting.getCode(),setting.getValue());
		
		if(getCommonService().isExist(Setting.class, "code", setting.getCode(), null,null)){
			renderJson("{success:false,id:"+setting.getId()+",name:'"+setting.getName()+"'}");
		}
		else{
			renderJson("{success:true,id:"+setting.getId()+",name:'"+setting.getName()+"'}");
		}
		
	}
	
	public void create() {
		getCommonService().save(setting);
		renderJson("{success:true,id:"+setting.getId()+"}");
	}
	@SuppressWarnings("unchecked")
	public void list() {
		
		List<Setting> settings = getCommonService().findAll(Setting.class, "position asc",null,null);
	    List<Map<String, Object>> jsonList = new ArrayList<Map<String,Object>>();
	    for(Setting m : settings){
	    	Map<String, Object> map = new HashMap<String, Object>();
	    	map.put("setting", m);
	    	
	    	jsonList.add(map);
	    }
	    JSONArray jsonObject = JSONArray.fromObject(jsonList);
		String jsonString = jsonObject.toString();
		renderJson(jsonString);
	}
	

	public void delete() {
		for(Integer id : ids){
			getCommonService().executeUpdate("delete Setting where id = ?", id);
		}
		
		renderJson("{success:true}");
	}
	

	
	public Setting getSetting() {
		return setting;
	}

	public void setSetting(Setting setting) {
		this.setting = setting;
	}
}
